<template>
  <div>
    <el-tree
      :props="menus"
      :load="loadNode"
      :default-expanded-keys="defaultExpandedKeys"
      @check="handleCheck"
      node-key="id"
      ref="memuTree"
      lazy
      show-checkbox>
    </el-tree>
    <div class="footer">
      <el-button @click="setChecked()">清空</el-button>
      <el-button @click="doSelectMenu">重置</el-button>
      <el-button type="primary" @click="doSelectMenu">确 定</el-button>
    </div>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'sys-role-rel-permission',
  props: {
    roleId: {
      type: Number
    }
  },
  data () {
    return {
      menus: {
        label: 'title',
        children: 'children',
        isLeaf: 'hasChildren'
      },
      defaultExpandedKeys: [],
      checkedKeys: [],
      randomKey: 0
    }
  },
  mounted () {
    // this.setChecked([3, 15, 18])
    // console.log(this.roleId, 'ggghh')
    // this.getCheckedKeys()
  },
  methods: {
    getCheckedKeys () {
      api.sysRole.findCheckedMenuByRoleId({ id: this.roleId }).then(res => {
        if (res) {
          this.defaultExpandedKeys = res.checkedKeys.halfCheckedKeys
          console.log(res.checkedKeys.checkKeys)
          this.checkedKeys = res.checkedKeys.checkKeys
        } else {
          this.checkedKeys = []
          this.defaultExpandedKeys = []
        }
        this.setChecked()
      })
    },
    loadNode (node, resolve) {
      var param = { parentId: 0 }
      if (node.level > 0) {
        param = { parentId: node.data.id }
      }
      api.sys_menu_list(param).then(res => {
        var res2 = res.map(e => {
          if (e.hasChildren === 0) {
            e.hasChildren = true
          } else if (e.hasChildren === 1) {
            e.hasChildren = false
          }
          return e
        })
        resolve(res2)
        this.setChecked()
      })
    },
    handleCheck (node, checkedNodes) {
    },
    setChecked () {
      this.$refs.memuTree.setCheckedKeys(this.checkedKeys)
    },
    doSelectMenu () {
      var checkKeys = this.$refs.memuTree.getCheckedKeys()
      var halfCheckedKeys = this.$refs.memuTree.getHalfCheckedKeys()
      console.log(checkKeys)
      console.log(halfCheckedKeys)
      var data = {}
      data.roleId = this.roleId
      data.checkedMenus = {
        checkKeys: checkKeys,
        halfCheckedKeys: halfCheckedKeys
      }
      api.sysRole.addMenu(data).then(res => {
        this.$message({ type: 'info', message: '已更新' })
      })
    }
  },
  watch: {
    roleId (val) {
      if (val) {
        // console.log(val, 'hhh')
        this.getCheckedKeys()
      }
    }
  }
}
</script>

<style lang="scss">
 .footer {
   margin-top: 30px;
 }
</style>
